<template>
    <div v-loading="loading || dataLoading">
        <div
            class="card-wrap flex justify-end card-padding"
            style="margin: 5px 20px 5px 20px"
        >
            <el-button @click="back">返回</el-button>
        </div>
        <Box>
            <div class="container" v-loading="dataLoading">
                <template v-for="conf in menus">
                    <div class="form" v-if="conf.formType == 2 && !loading">
                        <el-form
                            :model="conf.data"
                            ref="form"
                            label-width="80px"
                            :inline="false"
                            size="normal"
                        >
                            <el-form-item
                                v-for="item in conf.formConfig"
                                :label="item.label"
                                :rules="item.regList"
                                :prop="item.vModel"
                            >
                                <template v-if="item.tag == 'el-input'">
                                    <el-input
                                        v-model="conf.data[item.vModel]"
                                        :disabled="
                                            conf.state == 'disabled' ||
                                            item.disabled
                                        "
                                        v-bind="item"
                                    ></el-input>
                                </template>
                                <template v-if="item.tag == 'el-cascader'">
                                    <el-cascader
                                        v-model="conf.data[item.vModel]"
                                        :disabled="
                                            conf.state == 'disabled' ||
                                            item.disabled
                                        "
                                        v-bind="item"
                                    ></el-cascader>
                                </template>
                                <template v-if="item.tag == 'el-select'">
                                    <el-select
                                        v-model="conf.data[item.vModel]"
                                        :disabled="
                                            conf.state == 'disabled' ||
                                            item.disabled
                                        "
                                        v-bind="item"
                                    >
                                        <el-option
                                            v-for="e in item.options || []"
                                            :key="e.value"
                                            :label="e.label"
                                            :value="e.value"
                                        >
                                        </el-option>
                                    </el-select>
                                </template>
                                <template v-if="item.tag == 'el-date-picker'">
                                    <el-date-picker
                                        v-model="conf.data[item.vModel]"
                                        :disabled="
                                            conf.state == 'disabled' ||
                                            item.disabled
                                        "
                                        v-bind="item"
                                    ></el-date-picker>
                                </template>

                                <template v-if="item.tag == 'el-switch'">
                                    <el-switch
                                        v-model="conf.data[item.vModel]"
                                        :disabled="
                                            conf.state == 'disabled' ||
                                            item.disabled
                                        "
                                        v-bind="item"
                                    ></el-switch>
                                </template>
                                <template
                                    v-if="item.tag == 'el-checkbox-group'"
                                >
                                    <el-checkbox-group
                                        v-if="item.options"
                                        v-model="conf.data[item.vModel]"
                                        :disabled="
                                            conf.state == 'disabled' ||
                                            item.disabled
                                        "
                                        v-bind="item"
                                    >
                                        <el-checkbox
                                            v-for="(e, index) in item.options ||
                                            []"
                                            :label="e.value"
                                        >
                                            {{ e.label }}
                                        </el-checkbox>
                                    </el-checkbox-group>
                                </template>

                                <template v-if="item.tag == 'el-radio-group'">
                                    <el-radio-group
                                        v-model="conf.data[item.vModel]"
                                        :disabled="
                                            conf.state == 'disabled' ||
                                            item.disabled
                                        "
                                        v-bind="item"
                                    >
                                        <el-radio
                                            v-for="(e, index) in item.options ||
                                            []"
                                            :key="index"
                                            :label="e.value"
                                        >
                                            {{ e.label }}
                                        </el-radio>
                                    </el-radio-group>
                                </template>
                            </el-form-item>
                        </el-form>
                    </div>
                    <template v-if="conf.formType == 1 && !loading">
                        <div class="container_item" v-if="notEmpty(infoData)">
                            <component
                                v-if="notEmpty(conf.key)"
                                ref="chunk"
                                :is="conf.name"
                                v-model="details[conf.key]"
                                :state="conf.status"
                                :pageConfig="pageConfig"
                                :activityId="activityId"
                                :taskId="taskId"
                            >
                            </component>
                            <component
                                v-if="!notEmpty(conf.key)"
                                ref="chunk"
                                :is="conf.name"
                                v-model="infoData"
                                :state="conf.status"
                                :pageConfig="pageConfig"
                                :activityId="activityId"
                                :taskId="taskId"
                            >
                            </component>
                        </div>
                    </template>
                </template>
            </div>
            <template #right>
                <Check
                    :taskId="taskId"
                    :processId="processId"
                    :flag="flag"
                    :infoData="infoData"
                    :formData="formData"
                    :remark="remark"
                    @setRemark="setRemark"
                    :curreentActive="curreentActive"
                    :components="chunks"
                    :activities="activities"
                    :isSuspended="isSuspended"
                    :stageRemark="stageRemark"
                    :userAuthority="userAuthority"
                ></Check>
            </template>
        </Box>
    </div>
</template>

<script>
import Vue from "vue";
import Box from "@/components/DetailsPage/index_A.vue";
import Check from "./rightChunk.vue";
import * as apis from "@/api/flowable/examine/details/api.js";
import request from "@/utils/request";
import Cookies from "js-cookie";
export default {
    name: "Details",
    props: {},
    components: { Box, Check },
    computed: {
        processId() {
            return this.$route.query.processId;
        },
        flag() {
            return this.$route.query.flag;
        },
        type() {
            return this.$route.query.type;
        },
        isSuspended() {
            return this.$route.query.isSuspended;
        },
        status() {
            return this.$route.query.status;
        },
        state() {
            let status = "write";
            switch (this.flag) {
                case "1":
                    status = "readonly";
                    break;
                default:
                    status = "";
                    break;
            }
            return status;
        },
        taskId() {
            return this.$route.query.taskId;
        },
        activityId() {
            return this.$route.query.activityId;
        },
        mapList() {
            return {
                "finance/manage/paymentDetail/chunk/info/index.vue":
                    "paymentFormData",
                "finance/manage/paymentDetail/chunk/payment/index.vue":
                    "paymentFormData",
            };
        },
        flag() {
            return this.$route.query.flag;
        },
    },
    provide() {
        return {
            processId: this.processId,
            flag: this.flag,
            taskId: this.taskId,
        };
    },
    data() {
        return {
            loading: true,
            dataLoading: true,
            infoData: {},
            details: {},
            pageConfig: [],
            menus: [],
            menus_test: [],
            remark: "",
            formConfig: [],
            formData: [],
            stageRemark: "",
            curreentActive: {},
            chunks: [],
            activities: [],
            returnList: [],
            flowSquel: [],
            userAuthority:true
        };
    },
    watch: {
        stageRemark: {
            deep: true,
            handler: function (val) {
                this.stageRemark = val;
            },
        },
        // menus: {
        //     deep: true,
        //     handler: function (val) {
        //         let item = val?.find((e) => e.formType == 1);
        //         this.infoData = item.data;
        //     },
        // },
        // infoData: {
        //     deep: true,
        //     handler: function (val) {
        //         console.log(val);
        //     },
        // },
        // formData: {
        //     deep: true,
        //     handler: function (val) {
        //         console.log(val);
        //     },
        // },
    },
    async beforeMount() {
        try {
            this.dataLoading = true;
            // await this.getReturnList();
            // await this.getFlowRecord();
            // await this.getPageAddress();
            // await this.getData();
            Promise.all([
                // this.getReturnList(),
                this.getFlowRecord(),
                this.getPageAddress(),
                this.getData(),
            ]).then((res) => {
                this.dataLoading = false;
                this.initConfig();
            });
        } catch (error) {
            console.log(error);
        }

        // await this.getPageAddress();
        // await this.getData();
    },
    mounted() {
        if(Cookies.get("userAuthority")==0){
            this.userAuthority = true
        }else{
            this.userAuthority = false
        }
    },

    // activated() {
    //     try {
    //         this.dataLoading = true;
    //         Promise.all([
    //             this.getFlowRecord(),
    //             this.getPageAddress(),
    //             this.getData(),
    //         ]).then((res) => {
    //             this.dataLoading = false;
    //             this.initConfig();
    //         });
    //     } catch (error) {
    //         console.log(error);
    //     }
    // },
    methods: {
        back() {
            this.$router.back();
            this.$store.dispatch("tagsView/delView", this.$route);
        },
        setInput(conf, data) {
            conf.data = data;
            this.infoData = data;
        },
        // getReturnList() {
        //     return new Promise((resolve) => {
        //         let params = {
        //             taskId: this.taskId,
        //         };
        //         apis?.ReturnList(params)
        //             .then((res) => {
        //                 if (res.code == 200) {
        //                     this.returnList = res.data;
        //                 }
        //             })
        //             .finally(() => {
        //                 resolve();
        //             });
        //     });
        // },
        getFlowRecord() {
            return new Promise((resolve) => {
                let params = {
                    id: this.processId,
                };
                apis?.FlowRecord?.(params)
                    .then((res) => {
                        this.activities = res?.data ?? [];
                    })
                    .finally(() => {
                        resolve();
                    });
            });
        },
        setRemark(val) {
            this.remark = val;
        },
        formatState(val) {
            let status = "disabled";
            switch (val?.toString()) {
                case "0":
                    status = "write";
                    break;
                case "1":
                    status = "readonly";
                    break;
                case "2":
                    status = "hidden";
                    break;
            }
            return status;
        },
        submit() {},
        getData() {
            return new Promise((resolve) => {
                let params = {
                    processId: this.processId,
                };
                apis?.FlowVariables(params)
                    .then((res) => {
                        if (res.code == 200) {
                            // 可见的节点一部分后端返回，另一部分取路由参数的值（路由上是本节点，后端返回之前的节点）
                            const route =
                                this.$route.query?.activityId?.split(",");
                            this.flowSquel = res?.data?.flowSquel?.split(",");
                            // this.returnList = Array.from(new Set([...route,...route1]))
                            this.returnList = route;
                            this.stageRemark = res?.data.stageRemark;

                            if (
                                res?.data?.formData ??
                                res?.data?.startFormData
                            ) {
                                try {
                                    this.details = res.data;
                                    let data = JSON.parse(
                                        res?.data?.formData ??
                                            res?.data?.startFormData
                                    );
                                    this.infoData = data;
                                } catch (error) {
                                    this.infoData = {};
                                    console.log(error);
                                }
                            } else {
                                this.infoData = [];
                            }
                            if (res?.data?.customFormData) {
                                try {
                                    this.formData =
                                        JSON.parse(res?.data?.customFormData) ??
                                        [];
                                } catch (error) {
                                    this.formData = [];
                                }
                            } else {
                                this.formData = [];
                            }
                            // this.$emit("remark", res?.data?.remark);
                            this.remark = res?.data?.remark;
                        }
                    })
                    .finally(() => {
                        resolve();
                    });
            });
        },
        getPageAddress() {
            this.loading = true;
            return new Promise((res) => {
                let params = {
                    processId: this.processId,
                    flag: this.flag,
                    activityId: this.activityId,
                };
                apis?.PageAddress(params)
                    .then((res) => {
                        if (res.code == 200) {
                            this.pageConfig = res?.data ?? [];
                        }
                    })
                    .finally(() => {
                        this.loading = false;
                        res();
                    });
            });
        },

        initConfig() {
            let that = this;
            let activedIndex = this.pageConfig?.findIndex(
                (e) => e.activityId == this.activityId
            );
            if (activedIndex !== -1) {
                this.curreentActive = this.pageConfig?.[activedIndex];
            }
            // 正常流程
            if (this.returnList) {
                this.pageConfig?.map((item, index) => {
                    let historyIndex = this.returnList?.findIndex((e, i) => {
                        return e == item.activityId;
                    });
                    this.returnList.map((res) => {
                        // this.getOldInfo(res)
                        if (res == item.activityId) {
                            if (
                                historyIndex !== -1 ||
                                item.activityId == this.activityId
                            ) {
                                try {
                                    if (item.activityConfig.pageAddress) {
                                        item.activityConfig.pageAddress =
                                            JSON.parse(
                                                item.activityConfig.pageAddress
                                            );
                                    }
                                } catch (error) {
                                    console.log(error);
                                }
                                try {
                                    if (
                                        item.activityConfig.activityPermission
                                    ) {
                                        item.activityConfig.activityPermission =
                                            JSON.parse(
                                                JSON.parse(
                                                    item.activityConfig
                                                        ?.activityPermission
                                                )
                                            );
                                    }
                                } catch (error) {
                                    console.log(error);
                                }

                                try {
                                    item.activityConfig?.pageAddress?.forEach(
                                        (e) => {
                                            // e.formType == 1 是业务节点，只去当前页面 e.formType == 2是审批节点，需要展示本节点的自定义字段，以及前面一个节点的信息
                                            if (e.formType == 1) {
                                                e.pageAddress =
                                                    item.activityConfig.activityPermission[0].flowBusPageList;
                                                // 0：:可编辑 1：只读 2：隐藏
                                                // 页面状态设置为可编辑，模块可执行 可编辑 只读 隐藏3种状态 页面为只读，模块都是只读，页面是隐藏模块都是隐藏
                                                if (
                                                    item.activityConfig
                                                        .activityPermission[0]
                                                        .formStatus == 0 ||
                                                    item.activityConfig
                                                        .activityPermission[0]
                                                        .formStatus == 1
                                                ) {
                                                    e.pageAddress?.map(
                                                        (child) => {
                                                            let key =
                                                                Object.keys(
                                                                    this.mapList
                                                                ).find(
                                                                    (e) =>
                                                                        e ==
                                                                        child?.pageUrl
                                                                );
                                                            let data =
                                                                this.infoData;
                                                            let value =
                                                                this.mapList[
                                                                    key
                                                                ];
                                                            if (key) {
                                                                try {
                                                                    if (
                                                                        this
                                                                            .details[
                                                                            value
                                                                        ]
                                                                    ) {
                                                                        this.details[
                                                                            value
                                                                        ] =
                                                                            JSON.parse(
                                                                                this
                                                                                    .details[
                                                                                    value
                                                                                ]
                                                                            );
                                                                    } else {
                                                                        this.details[
                                                                            value
                                                                        ] = {};
                                                                    }
                                                                } catch (error) {
                                                                    console.log(
                                                                        error
                                                                    );
                                                                }
                                                            }
                                                            if (
                                                                item
                                                                    .activityConfig
                                                                    .activityPermission[0]
                                                                    .formStatus ==
                                                                1
                                                            ) {
                                                                // 页面只读，模块只读
                                                                if (
                                                                    child.formStatus !==
                                                                    2
                                                                ) {
                                                                    that.initComponent(
                                                                        child.name,
                                                                        child.pageUrl,
                                                                        data,
                                                                        1,
                                                                        1,
                                                                        value
                                                                    );
                                                                }
                                                            } else {
                                                                if (
                                                                    child.formStatus !==
                                                                    2
                                                                ) {
                                                                    // 页面可编辑 子页面任意搭配
                                                                    let state =
                                                                        this.formatState(
                                                                            child.formStatus
                                                                        ); // 后端返回字段转化
                                                                    that.initComponent(
                                                                        child.name,
                                                                        child.pageUrl,
                                                                        data,
                                                                        child.formStatus,
                                                                        1,
                                                                        value
                                                                    );
                                                                }
                                                            }
                                                        }
                                                    );
                                                } else {
                                                }
                                            }
                                            if (e.formType == 2) {
                                                // 审批节点需要添加之前节点的页面
                                                const oldList =
                                                    this.getOldInfo(res);

                                                let newList = JSON.parse(
                                                    JSON.parse(
                                                        oldList.activityConfig
                                                            .activityPermission
                                                    )
                                                );
                                                let addList =
                                                    newList[0].flowBusPageList;
                                                if (
                                                    newList[0].formStatus ==
                                                        0 ||
                                                    newList[0].formStatus == 1
                                                ) {
                                                    addList.map((child) => {
                                                        if (
                                                            newList[0]
                                                                .formStatus == 1
                                                        ) {
                                                            // 页面只读，模块只读
                                                            if (
                                                                child.formStatus !==
                                                                2
                                                            ) {
                                                                that.initComponent(
                                                                    child.name,
                                                                    child.pageUrl,
                                                                    that.infoData,
                                                                    1,
                                                                    1
                                                                );
                                                            }
                                                        } else {
                                                            if (
                                                                child.formStatus !==
                                                                2
                                                            ) {
                                                                // 页面可编辑 子页面任意搭配
                                                                let state =
                                                                    this.formatState(
                                                                        child.formStatus
                                                                    ); // 后端返回字段转化
                                                                that.initComponent(
                                                                    child.name,
                                                                    child.pageUrl,
                                                                    that.infoData,
                                                                    child.formStatus,
                                                                    1
                                                                );
                                                            }
                                                        }
                                                    });
                                                } else {
                                                    console.log(123);
                                                }
                                                // 自定义表单
                                                e.customForm = JSON.parse(
                                                    e.customForm
                                                );
                                                let state =
                                                    index == activedIndex
                                                        ? "write"
                                                        : "disabled";
                                                let currentFormData =
                                                    this.formData?.find(
                                                        (child) =>
                                                            child.formId ==
                                                            item.activityConfig
                                                                .formId
                                                    );
                                                let obj = {};
                                                if (!currentFormData) {
                                                    obj = Vue.observable({
                                                        formId: item
                                                            .activityConfig
                                                            .formId,
                                                        data: {},
                                                    });
                                                    this.formData.push(obj);
                                                }
                                                that.initForm(
                                                    e.customForm,
                                                    currentFormData?.data ??
                                                        obj?.data,
                                                    this.state ?? state,
                                                    item.activityConfig.formId,
                                                    e.formType
                                                );
                                            }
                                        }
                                    );
                                } catch (error) {
                                    console.log(error);
                                }
                            }
                        }
                    });
                });
            } else {
                // 拒绝的流程
                let list = []; // 驳回节点前所有的节点
                let customList = []; // 自定义节点
                let businessList = []; // 业务节点
                if (this.flowSquel.length > 0) {
                    this.flowSquel.map((item) => {
                        this.pageConfig.map((res) => {
                            if (item == res.activityId) {
                                res.activityConfig.activityPermission = res
                                    .activityConfig.activityPermission
                                    ? JSON.parse(
                                          JSON.parse(
                                              res.activityConfig
                                                  .activityPermission
                                          )
                                      )
                                    : "";
                                res.activityConfig.pageAddress = res
                                    .activityConfig.pageAddress
                                    ? JSON.parse(res.activityConfig.pageAddress)
                                    : "";
                                list.push(res);
                            }
                        });
                    });
                }
                list.map((info) => {
                    if (
                        info.activityConfig.activityPermission[0].formType == 1
                    ) {
                        businessList.push(info);
                    } else if (
                        info.activityConfig.activityPermission[0].formType == 2
                    ) {
                        customList.push(info);
                    }
                });
                if (customList.length > 0) {
                    customList.map((res) => {
                        this.initForm(
                            res.activityConfig.pageAddress.customForm,
                            currentFormData?.data ?? obj?.data,
                            this.state ?? state,
                            res.activityConfig.formId,
                            res.activityConfig.pageAddress[0].formType
                        );
                    });
                }
                if (businessList.length > 0) {
                    let childList = businessList[businessList.length - 1];
                    childList.activityConfig.activityPermission[0].flowBusPageList.map(
                        (child) => {
                            this.initComponent(
                                child.name,
                                child.pageUrl,
                                this.infoData,
                                1,
                                1
                            );
                        }
                    );
                }
            }

            this.$nextTick(() => {
                this.chunks = this.$refs.chunk;
            });
        },
        // 获取当前节点之前的节点信息
        getOldInfo(node) {
            if (node) {
                // 根据节点名后缀，给模块新增数字id,方便排序
                // let id = Number(node.split("_")[1]);
                let arr = JSON.parse(JSON.stringify(this.pageConfig));
                // arr.map((res) => {
                //     let id = res.activityId.split("_")[1];
                //     this.$set(res, "id", Number(id));
                // });
                let targertIndex = arr.findIndex(
                    (item) => item.activityId == node
                );
                if (targertIndex > 0) {
                    let list = arr.slice(0, targertIndex);
                    let list2 = [];
                    list.map((info) => {
                        info.activityConfig.pageAddress = JSON.parse(
                            info.activityConfig.pageAddress
                        );
                        if (info.activityConfig.pageAddress[0].formType == 1) {
                            list2.push(info);
                        }
                    });
                    // list2.sort((a, b) => {
                    //     return a.id - b.id;
                    // });
                    return list2[list2.length - 1];
                }
                // let list1 = [];
                // // 获取当前节点之前的数据
                // arr.map((item) => {
                //     if (item.id < id) {
                //         list1.push(item);
                //     }
                // });
                // let list2 = [];
                // 获取业务节点
            }
        },

        initComponent(fileName, filePath, data, state, formType, key) {
            // fileName:模块名称 filePath:模块地址 data：整体数据 state:模块状态 formType:自定义模块还是业务模块
            try {
                // let fileName = this.filePathToName(filePath);
                let comIndex = this.menus.findIndex((item) => {
                    return item.name == fileName;
                });
                if (comIndex !== -1) {
                    this.menus.splice(comIndex, 1);
                    // this.$set(com, "state", state);
                }
                let path = filePath.replace(/\\/g, "/");
                let path_filter = path.split("src/views/");
                let path_end = "";
                if (path_filter?.length > 0) {
                    path_end = path_filter.slice(-1);
                }

                let path0 = path_end?.[0];
                if (path0 == "quota/apply/details/main.vue") {
                    console.error("临时策略，更改额度流程图表单后删除");
                    path0 = "quota/forecast/details_approve/index.vue";
                }
                console.log(path_end);
                const component = require(`../../../../views/${path0}`).default;
                let status = "write";
                if (state == 0) {
                    status = "write";
                } else if (state == 1) {
                    status = "readonly";
                } else if (state == 2) {
                    status = "disabled";
                }
                this.$options.components[fileName] = component;
                let obj = {
                    name: fileName,
                    data: data ?? this.infoData,
                    status: this.status || status,
                    formType,
                    key,
                };

                this.menus_test.push(obj);
                this.menus.push(obj);
            } catch (err) {
                console.error(`引入组件/views/${filePath}失败`);
            }
        },
        initForm(
            formConfig = [],
            data = {},
            state = "disabled",
            formId,
            formType
        ) {
            let currentFormData = this.formData?.find(
                (child) => child.formId == formId
            );
            let comIndex = this.menus.findIndex((item) => {
                return item?.formId == formId;
            });
            if (comIndex !== -1) {
                this.menus.splice(comIndex, 1);
                // this.$set(com, "state", state);
            }
            let obj = Vue.observable({
                formConfig,
                formId,
                data: currentFormData.data,
                state,
                formType,
            });
            this.menus_test.push(obj);
            this.menus.push(obj);
        },
        // filePathToName(filepath) {
        //     let str = "";
        //     str = filepath?.replace(/(\/|.vue)/g, "") ?? "";
        //     return str;
        // },
    },
};
</script>

<style lang="scss" scoped>
.container {
    min-height: calc(100vh - 84px);

    // background: #fff;
    .container_item {
        margin-bottom: 15px;
    }
}

.form {
    background-color: #fff;
    padding: 20px;
    border-radius: 10px;
    margin: 20px 0;
    margin-top: 0;
}
</style>
